package com.lottery.ruok.lottrey.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lottery.ruok.lottrey.R;

import com.lottery.ruok.lottrey.activity.ActivitiesViewpagerActivity;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.ext.GlideExt;
import com.lottery.ruok.lottrey.fragment.ChildActivitiesListFragment;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.JoinActivityRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityListResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.JoinActivityResponse;
import com.lottery.ruok.lottrey.ui.widget.ActivitiesItemView;
import com.lottery.ruok.lottrey.ui.widget.ActivitiesSingleMissions;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.DisplayUtil;
import com.lottery.ruok.lottrey.utils.TimeUtil;

import java.util.ArrayList;
import java.util.HashMap;

import utils.Utils;

public class ActivitiesAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private RecyclerView mRecyclerView;
    private Context mContext;
    private ArrayList<ActivityListResponse.ListBean> mData;

    private final int VIEW_TYPE_EMPTY = 0;
    private final int VIEW_TYPE_ITEM = 1;
    private ChildActivitiesListFragment.OnRefreshListener mOnRefreshListener;

    private final HashMap<Integer, Boolean> isOpen = new HashMap<>();

    public ActivitiesAdapter(Context context, ArrayList<T> data, ChildActivitiesListFragment.OnRefreshListener onRefreshListener,RecyclerView recyclerView) {
        this.mContext = context;
        this.mData = (ArrayList<ActivityListResponse.ListBean>) data;
        this.mOnRefreshListener = onRefreshListener;
        this.mRecyclerView = recyclerView;
    }

    public void setData(ArrayList<T> data) {
        this.mData = (ArrayList<ActivityListResponse.ListBean>) data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_EMPTY) {
            final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.no_net_layout2, parent, false);
            return new EmptyViewHolder(view);
        } else {
            View view = View.inflate(mContext, R.layout.activities_item_layout, null);
            return new ActivitiesViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder hd, final int position) {
        if (hd instanceof ActivitiesViewHolder) {
            final ActivitiesViewHolder holder = (ActivitiesViewHolder) hd;
            Glide.with(mContext)
                    .load(mData.get(position).getBanner())
                    .into(holder.ivActivitiesBg);
            holder.llContainer.removeAllViews();
            if (mData.get(position).getShort_time() != null) {
                holder.textTime.setText("活动期间:"+mData.get(position).getShort_time());
            }

            holder.textActivitiesName.setText(mData.get(position).getName());

            if (mData.get(position).getMissions().size() == 1) {
                ActivitiesSingleMissions activitiesSingleMissions = new ActivitiesSingleMissions(mContext);
                activitiesSingleMissions.setData(mData.get(position).getMissions().get(0), mData.get(position).getId() + "", mData.get(position).getStatus());
                holder.llContainer.addView(activitiesSingleMissions);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) activitiesSingleMissions.getLayoutParams();
                layoutParams.width = (int) DisplayUtil.dip2px(320, mContext);
                layoutParams.topMargin = 10;
                layoutParams.bottomMargin = 10;
                activitiesSingleMissions.setLayoutParams(layoutParams);
                holder.missionsTitle.setVisibility(View.GONE);
            } else {
                int firstProcessing = 1;
                for (int i = 0; i < mData.get(position).getMissions().size(); i++) {
                    ActivitiesItemView activitiesItemView = new ActivitiesItemView(mContext);
                    ActivityListResponse.ListBean.MissionsBean missionsBean = mData.get(position).getMissions().get(i);
                    if (missionsBean.getStatus() == 1 && firstProcessing == 1) {//这段代码主要是为了只让任务有发光效果，阶段奖励和终极大奖不发光
                        firstProcessing = -1;
                    } else if (missionsBean.getStatus() == 1 && firstProcessing == -1){
                        missionsBean.setStatus(0);
                    }
                    activitiesItemView.setData(mData.get(position).getMissions(),missionsBean, mData.get(position).getId() + "", mData.get(position).getStatus(), i);
                    activitiesItemView.setProgressBarVisible();
                    holder.llContainer.addView(activitiesItemView);
                    if (missionsBean.getStatus() == 1 && mData.get(position).getStatus() == 2) {
                        holder.missionsTitle.setVisibility(View.VISIBLE);
                        holder.missionsTitle.setText(missionsBean.getTitle().getValue());
                        holder.missionsTitle.setTextColor(Color.parseColor(missionsBean.getTitle().getColor()));
                      /*  TextView activitiesContent = activitiesItemView.findViewById(R.id.activities_content);
                        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) activitiesContent.getLayoutParams();
                        lp.leftMargin = (int) DisplayUtil.dip2px(33, mContext);
                        activitiesContent.setLayoutParams(lp);*/
                    } else {
                        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) activitiesItemView.getLayoutParams();
                        lp.topMargin = (int) DisplayUtil.dip2px(5f, mContext);
                        activitiesItemView.setLayoutParams(lp);
                    }
                }
            }
//            if (isOpen.get(position) == null) {
//                holder.llActivitiesProgress.setVisibility(View.VISIBLE);
//                holder.progressbarInfo.setBackgroundResource(R.drawable.seek_tops_hollow);
//                holder.progressbarInfo.setText("收起进度");
//                holder.progressbarInfo.setTextColor(Color.parseColor("#9067ff"));
//            } else {
//                if (isOpen.get(position)) {
//                    holder.llActivitiesProgress.setVisibility(View.VISIBLE);
//                    holder.progressbarInfo.setBackgroundResource(R.drawable.seek_tops_hollow);
//                    holder.progressbarInfo.setText("收起进度");
//                    holder.progressbarInfo.setTextColor(Color.parseColor("#9067ff"));
//                } else {
//                    holder.llActivitiesProgress.setVisibility(View.GONE);
//                    holder.progressbarInfo.setBackgroundResource(R.drawable.seek_tops);
//                    holder.progressbarInfo.setText("查看进度");
//                    holder.progressbarInfo.setTextColor(Color.parseColor("#ffffff"));
//                }
//            }
//
//            //查看进度
//            holder.progressbarInfo.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (holder.llActivitiesProgress.getVisibility() != View.VISIBLE) {
//                        holder.llActivitiesProgress.setVisibility(View.VISIBLE);
//                        holder.progressbarInfo.setBackgroundResource(R.drawable.seek_tops_hollow);
//                        holder.progressbarInfo.setText("收起进度");
//                        holder.progressbarInfo.setTextColor(Color.parseColor("#9067ff"));
//                        isOpen.put(position, true);
//                    } else {
//                        holder.llActivitiesProgress.setVisibility(View.GONE);
//                        holder.progressbarInfo.setBackgroundResource(R.drawable.seek_tops);
//                        holder.progressbarInfo.setText("查看进度");
//                        holder.progressbarInfo.setTextColor(Color.parseColor("#ffffff"));
//                        isOpen.put(position, false);
//                    }
//                }
//            });
            //进入详情
            holder.ivActivitiesBg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ActivitiesViewpagerActivity.class);

                    intent.putExtra("data", mData);
                    intent.putExtra("position", position);
                    mContext.startActivity(intent);
                }
            });
            //参与活动
            holder.joining.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (UserInfo.getToken().equals("")) {
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        mContext.startActivity(intent);
                        ((Activity) mContext).overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                    } else {
                        joinActivity(mData.get(position).getId() + "");
                    }
                }
            });
            if (mData.get(position).getJoined() == 1) {
                holder.joining.setVisibility(View.GONE);
            } else {
                holder.joining.setVisibility(View.VISIBLE);
                holder.llActivitiesProgress.setVisibility(View.GONE);
            }

            //获取是否有可以领奖
            holder.leftIcon.setVisibility(View.GONE);
            boolean isReceive = false;
            for (ActivityListResponse.ListBean.MissionsBean missionsBean : mData.get(position).getMissions()) {
                if (missionsBean.getStatus() == 3) {
                    isReceive = true;
                }
            }
            if (isReceive) {
                holder.leftIcon.setBackgroundResource(R.mipmap.icon_price_enable);
                holder.leftIcon.setVisibility(View.VISIBLE);
            } else {
                ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans1 = new ArrayList<>();
                ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans2  = mData.get(position).getMissions();
                for (ActivityListResponse.ListBean.MissionsBean missionsBean : missionsBeans2) {
                    if (missionsBean.getStatus() == 4) {
                        missionsBeans1.add(missionsBean);
                    }
                }
                if (missionsBeans1.size() == missionsBeans2.size()) {
                    holder.leftIcon.setBackgroundResource(R.mipmap.yilingwantupian);
                    holder.leftIcon.setVisibility(View.VISIBLE);
                }
            }
            if (mData.get(position).getDaily_reset() == 1) {
                holder.dailyResetImage.setVisibility(View.VISIBLE);
                GlideExt.setBackgroundDrawable(mContext, mData.get(position).getStyles().getDaily_reset(), holder.dailyResetImage, null);
            } else {
                holder.dailyResetImage.setVisibility(View.GONE);
            }

            switch (mData.get(position).getStatus()) {
                //等待发起
                case 1:
                    holder.statusLayout.setVisibility(View.GONE);
                    holder.llActivitiesProgress.setVisibility(View.VISIBLE);
                    break;
                //进行中
                case 2:
                    if (mData.get(position).getJoined() == 1) {
                        holder.statusLayout.setVisibility(View.GONE);
                        holder.llActivitiesProgress.setVisibility(View.VISIBLE);
                    }else{
                        holder.statusLayout.setVisibility(View.VISIBLE);
                        holder.imgStatus.setVisibility(View.GONE);
                        holder.llActivitiesProgress.setVisibility(View.GONE);
                    }
                    break;
                //过期
                case 3:
                    holder.statusLayout.setVisibility(View.VISIBLE);
                    holder.llActivitiesProgress.setVisibility(View.GONE);

                    holder.imgStatus.setVisibility(View.VISIBLE);
                    holder.imgStatus.setImageResource(R.mipmap.expired);

                    holder.joining.setVisibility(View.GONE);
                    break;
                //暂停
                case 4:
                    holder.statusLayout.setVisibility(View.VISIBLE);
                    holder.llActivitiesProgress.setVisibility(View.GONE);

                    holder.imgStatus.setVisibility(View.VISIBLE);
                    holder.imgStatus.setImageResource(R.mipmap.pause);
                    holder.joining.setVisibility(View.GONE);
                    break;
                case 102: // 已经完成的
                    // 已完成里面 也分为 是否已经领取完 和没有领取完
                    if(isReceive){
                        // 如果没有领取完
                        holder.statusLayout.setVisibility(View.GONE);
                        holder.llActivitiesProgress.setVisibility(View.VISIBLE);
                    }else{
                        holder.statusLayout.setVisibility(View.VISIBLE);
                        holder.llActivitiesProgress.setVisibility(View.GONE);
                        holder.imgStatus.setVisibility(View.VISIBLE);
                        holder.joining.setVisibility(View.GONE);
                        holder.imgStatus.setImageResource(R.mipmap.icon_all_finished);
                    }
                    break;
                case 101: // 可参与的
                    holder.statusLayout.setVisibility(View.VISIBLE);
                    holder.llActivitiesProgress.setVisibility(View.GONE);

                    holder.imgStatus.setVisibility(View.GONE);
                    holder.joining.setVisibility(View.VISIBLE);

                    break;
            }
        } else if (hd instanceof EmptyViewHolder) {
            EmptyViewHolder holder = (EmptyViewHolder) hd;
            holder.view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnRefreshListener.onRefresh();
                }
            });
        }

    }

    //参与活动
    private void joinActivity(final String activityID) {
        RetrofitBase.getRetrofit().create(JoinActivityRequest.class)
                .getResult(UserInfo.getToken(), activityID)
                .compose(RxHelper.<JoinActivityResponse>handleResult())
                .subscribe(new RxSubscribe<JoinActivityResponse>(mContext) {
                    @Override
                    protected void _onNext(JoinActivityResponse joinActivityResponse) {
                        Utils.showToast("参与成功！");
                        mOnRefreshListener.onRefresh();
                    }
                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }


    @Override
    public int getItemCount() {
        if (mData == null) {
            return 1;
        }
        return mData.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mData == null) {
            return VIEW_TYPE_EMPTY;
        } else {
            return VIEW_TYPE_ITEM;
        }
    }
}


class ActivitiesViewHolder extends RecyclerView.ViewHolder {
    ImageView ivActivitiesBg;
    TextView textTime;
    TextView textInfo;
    TextView textActivitiesName;
    CardView cardView;
    LinearLayout llContainer;
    LinearLayout llActivitiesProgress;
    Button joining;
    ImageView imgStatus;
    TextView missionsTitle;
    ImageView leftIcon;
    ImageView dailyResetImage;
    RelativeLayout statusLayout;

    public ActivitiesViewHolder(View itemView) {
        super(itemView);
        llActivitiesProgress = itemView.findViewById(R.id.activities_progress);
        llContainer = itemView.findViewById(R.id.ll_container);
        textInfo = itemView.findViewById(R.id.text_info);
        ivActivitiesBg = itemView.findViewById(R.id.iv_activities_bg);
        textTime = itemView.findViewById(R.id.text_time);
        textActivitiesName = itemView.findViewById(R.id.text_activities_name);
        cardView = itemView.findViewById(R.id.card_view);
        llContainer = itemView.findViewById(R.id.ll_container);
        joining = itemView.findViewById(R.id.joining);
        imgStatus = itemView.findViewById(R.id.img_status);
        missionsTitle = itemView.findViewById(R.id.missions_title);
        leftIcon = itemView.findViewById(R.id.left_icon);
        dailyResetImage = itemView.findViewById(R.id.iv_daily_reset);
        statusLayout = itemView.findViewById(R.id.activities_status_layout);
    }

}

class EmptyViewHolder extends RecyclerView.ViewHolder {
    View view;

    public EmptyViewHolder(View itemView) {
        super(itemView);
        view = itemView;
    }
}
